package com.htg.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Looper;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class UtilImage {


    public static void compressImageFile(File src, File file, int targetSizeInKB) throws IOException {
        //
        if (Looper.myLooper() == Looper.getMainLooper()) {
            throw new IllegalStateException("This method must be called from a background thread.");
        }
        //
        Bitmap bitmap = getBitmapFromFile(src);
        byte[] compressedImage = compressImageToTargetSize(bitmap, targetSizeInKB);
        saveCompressedImage(compressedImage, file);
    }

    private static void saveCompressedImage(byte[] compressedImage, File file) throws IOException {
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(compressedImage);
        fileOutputStream.flush();
        fileOutputStream.close();
    }

    private static byte[] compressImageToTargetSize(Bitmap bitmap, int targetSizeInKB) {
        int quality = 100;
        byte[] compressedImage = compressBitmap(bitmap, quality);

        while (compressedImage.length / 1024 > targetSizeInKB && quality > 0) {
            quality -= 5;
            compressedImage = compressBitmap(bitmap, quality);
        }
        return compressedImage;
    }

    private static byte[] compressBitmap(Bitmap bitmap, int quality) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }

    private static Bitmap getBitmapFromFile(File src) {
        return BitmapFactory.decodeFile(src.getAbsolutePath());
    }


}
